﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;


using CE.User;
using CE.CarInsurance;
using CE.Global;
using CE.Database;
using CE.Configuration;
using CE.Company;
using CE.Mail;
using BKI;

public partial class car_insurance_class_2plus : MyLanguageBasePage
{
    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;
    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.CIClass2PlusTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.CIClass2PlusKeyword;
        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.CIClass2PlusDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        if (Session[CE.Global.General.UserId] == null)
        {
            hplLogin.Visible = true;
        }
        else
        {
            hplLogin.Visible = false;
        }

        if (Session[General.CarPolicyId] != null && Session[General.IsCarRestoreResult] != null)
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/quote-results.aspx", Page);
            //Response.Redirect(_redirectUrl);
        }


        if (Page.ClientScript.IsStartupScriptRegistered("addScriptShowHideAll") == false)
        {
            Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScriptShowHideDriver", "ShowHideAll()", true);
        }

        if (Session[General.CarId] != null)
        {
            bool _iscomplete = false;
            MyDatabase _db = new MyDatabase();
            string strSql = "SELECT IsComplete FROM [tblUserResult] WHERE ResultType = 'CI' AND ID1 = " + Session[General.CarId].ToString();
            object _objIsComplete = _db.ExecuteScalarSqlStatement(strSql);
            if (_objIsComplete != null)
            {
                _iscomplete = Convert.ToBoolean(_objIsComplete.ToString());
            }


            if (_iscomplete == true && Session[General.UserId] != null)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else if (_iscomplete == true)
            {
                General.ClearAllSession(this.Page, "ALL");
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/car-and-policy-details.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
        }

        if (!Page.IsPostBack)
        {
            HtmlControl htmlClass = (HtmlControl)Master.FindControl("cls2plus");
            htmlClass.Attributes.Add("class", "selected");

            Session["CIMSG"] = null;
            Session["UMMSG"] = null;
            if (Session[General.UserId] == null)
            {
                //ibtSaveClose.Visible = false;
            }
            else
            {
                if (Session[CE.Global.General.UserTypeId] != null && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider))
                {
                    //ibtSaveClose.Visible = false;
                }
                else
                {
                    //ibtSaveClose.Visible = false;
                }
            }

            HyperLink _lnkTest = new HyperLink();

            //ibtSaveClose.Attributes.Add("onmouseover", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.SaveCloseButtonHoverImageUrl) + "';");
            //ibtSaveClose.Attributes.Add("onmouseout", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.SaveCloseButtonImageUrl) + "';");
            //ibtNext.Attributes.Add("onmouseover", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.NextButtonHoverImageUrl) + "';");
            //ibtNext.Attributes.Add("onmouseout", "this.src='" + _lnkTest.ResolveClientUrl(Resources.ImageResource.NextButtonImageUrl) + "';");
            txtAccModAmount.Attributes.Add("onblur", "ShowValidationEffectThree('" + txtAccModAmount.ClientID + "','" + rfvAccModAmount.ClientID + "','" + revAccModAmount.ClientID + "','" + csvAccModAmount.ClientID + "');");
            _lnkTest = null;


            DataTable dtPreInsurerComp = General.GetComboItem(Resources.DBTable.PreInsurer, Resources.DBTable.OrderByField, true);
            ddlCurInsuranceCompany.DataSource = dtPreInsurerComp;
            ddlCurInsuranceCompany.DataTextField = dtPreInsurerComp.Columns[0].ColumnName.ToString();
            ddlCurInsuranceCompany.DataValueField = dtPreInsurerComp.Columns[1].ColumnName.ToString();
            ddlCurInsuranceCompany.DataBind();
            ddlCurInsuranceCompany.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));

            //GenerateCarMakeModel();
            //CAR POLICY DETAILS 
            CultureInfo ci = CultureInfo.CurrentCulture;

            DateTime dtNow = new DateTime();
            dtNow = General.GetUTCDateTime();
            for (int i = 2; i < 61; i++)
            {
                DateTime dtTemp = dtNow.AddDays(i);
                string strDate = dtTemp.Date.Day.ToString("00") + dtTemp.Date.Month.ToString("00") + dtTemp.Date.Year.ToString("0000");
                ddlCoverageComDate.Items.Add(new ListItem(dtTemp.ToString("dd/MMMM/yyyy", ci), strDate));
            }
            ddlCoverageComDate.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));

            //DataTable dtNCD = General.GetComboItem("NCDNextClaim", "[NCDNextId]", true);

            //ddlNCB.Items.Clear();
            //if (dtNCD != null && dtNCD.Rows.Count > 0)
            //{
            //    for (int i = 0; i < dtNCD.Rows.Count; i++)
            //    {
            //        if (Convert.ToInt32(dtNCD.Rows[i][1].ToString()) >= 0)
            //        {
            //            ddlNCB.Items.Add(new ListItem(dtNCD.Rows[i][0].ToString(), dtNCD.Rows[i][1].ToString()));
            //        }
            //    }
            //}
            //ddlNCB.Items.Insert(0, new ListItem("Select", "-1"));
            //dtNCD = null;

            LoadManufactYearList();
            ClearAllList();
            //rdoNoAccMod.Checked = true;

            if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
            {
                //Int64 _ceuserid = 0;
                //if (Session[General.UserId] != null)
                //{
                //    _ceuserid = Convert.ToInt64(Session[General.UserId]);
                //}
                Int64 _cecarid = Convert.ToInt64(Session[General.CarId]);
                Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                ShowCarAndPolicyDetail(_cecarid, _cepolicyid, 0);
                DriverSetting();
                OtherValidation();
            }
            else
            {
                DriverSetting();
            }
            //============
            //int _startYear = General.GetUTCDateTime().Year - 10;
            //int _endYear = General.GetUTCDateTime().Year;
            //for (int i = _endYear; i >= _startYear; i--)
            //{
            //    ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            //}
            //ddlManufactYear.Items.Clear();
            //ddlManufactYear.Items.Insert(0, new ListItem("Select", "-1"));
            //LoadManufactYearList();

            //ddlInsuranceType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlInsuranceType.ClientID + "','" + rfvInsuranceType.ClientID + "');");
            //ddlGarageType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlGarageType.ClientID + "','" + rfvGarageType.ClientID + "');");

            ddlManufactYear.Attributes.Add("onblur", "ShowValidationEffect('" + ddlManufactYear.ClientID + "','" + rfvManufactYear.ClientID + "');");
            ddlCarMake.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCarMake.ClientID + "','" + rfvCarMake.ClientID + "');");
            ddlModelBodyCCDoor.Attributes.Add("onblur", "ShowValidationEffect('" + ddlModelBodyCCDoor.ClientID + "','" + rfvModelBodyCCDoor.ClientID + "');");
            ddlVehicleType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlVehicleType.ClientID + "','" + rfvVehicleType.ClientID + "');");

            ddlProvinceRegistration.Attributes.Add("onblur", "ShowValidationEffect('" + ddlProvinceRegistration.ClientID + "','" + rfvProvinceRegistration.ClientID + "');");
            //ddlUseOfVehicle.Attributes.Add("onblur", "ShowValidationEffect('" + ddlUseOfVehicle.ClientID + "','" + rfvUseOfVehicle.ClientID + "');");
            //ddlNCB.Attributes.Add("onfocus", "JT_ShowTwo('/tooltips/ncdrenew.htm?width=550', '" + ddlNCB.ClientID + "', 'NCD Discount'); return true;");
            //ddlNCB.Attributes.Add("onblur", "$('#JT').remove();ShowValidationEffect('" + ddlNCB.ClientID + "','" + rfvNCB.ClientID + "');");
            ddlNCB.Attributes.Add("onblur", "ShowValidationEffect('" + ddlNCB.ClientID + "','" + rfvNCB.ClientID + "');");

            ddlCurInsuranceCompany.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCurInsuranceCompany.ClientID + "','" + rfvCurInsuranceCompany.ClientID + "');");
            ddlCoverageComDate.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCoverageComDate.ClientID + "','" + rfvCoverComDate.ClientID + "');");

            //============
            usrDOB.StartYear = General.GetUTCDateTime().Year - 75;
            usrDOB.EndYear = General.GetUTCDateTime().Year - 18;
            txtEmailAddress.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmailAddress.ClientID + "','" + rfvEmail.ClientID + "','" + rfvEmailValid.ClientID + "');");
            txtConfirmEmailAddress.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtConfirmEmailAddress.ClientID + "','" + rfvConfirmEmail.ClientID + "','" + rfvConfirmEmailValid.ClientID + "');");
            txtSurName.Attributes.Add("onblur", "ShowValidationEffect('" + txtSurName.ClientID + "','" + rfvSurName.ClientID + "');");

            //


            if (rdoYesClaimLastYear.Checked || rdoNoClaimLastYear.Checked) txtAnyClaim.Text = "1";
            //if (rdoYesRedPlate.Checked || rdoNoRedPlate.Checked) txtRedPlate.Text = "1";
            if (rdoYesCTPL.Checked || rdoNoCTPL.Checked) txtCTPL.Text = "1";

            //rdoYesClaimLastYear.Attributes.Add("onmouseover", "JT_ShowTwo('/tooltips/ncdlogic.htm?width=550', '" + rdoYesClaimLastYear.ClientID + "', 'NCD Discount'); return true;");
            //rdoYesClaimLastYear.Attributes.Add("onclick", "$('#JT').remove();");
            //rdoYesClaimLastYear.Attributes.Add("onmouseout", "$('#JT').remove();");
            //disable tab
            //hplCarResults.NavigateUrl = "";
            //hplCarDetails.NavigateUrl = "";

            Page.Form.DefaultButton = ibtNext.UniqueID;

            General.ClearAllSession(this.Page, "CI");
            Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();

            lblCultureInfo.Value = HttpContext.Current.Session["Language"].ToString();
            // Profile
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                divExisting.Visible = false;
                checkIsAgreement.Visible = false;
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
                if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Customer))
                {
                    ShowCustomerDetail(_userId);
                    //btnUpdateCarProfile.Visible = false;
                }
                else if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider))
                {
                    ShowCustomerDetail(_userId);
                }
            }
            // change for Insurance Type
            
        }
    }


    protected void ibtSaveClose_Click(object sender, ImageClickEventArgs e)
    {
        //CheckValidation();
        OtherValidation();
        if (!DriverValidation())
        {
            //txtDriverValid.Text = "Not Valid";
        }
        else
        {
            //txtDriverValid.Text = "Valid";
        }
        //LoadCarModelList();
        ChangeValidationEffectServerSide("cardetail");
        Page.Validate("cardetail");
        if (Page.IsValid)
        {
            if (Save())
            {
                //BKICalculation();
                lblMessage.Text = "Saved successfully!";
                General.ClearAllSession(this.Page, "LOGOUT");
                //Response.Redirect("~/user/usermessage.aspx?mt=CI&ec=501");
                _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                Session["UMMSG"] = "CI,501";
                Response.Redirect(_redirectUrl);
            }
            else
            {
                lblMessage.Text = "Saving did NOT succeed!";
            }
        }
        else
        {
            lblMessage.Text = "Please fill all require fields completly and correctly.";
        }
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        //CheckValidation();
        OtherValidation();
        DriverValidation();
        ChangeValidationEffectServerSide("cardetail");

        if (CheckClaimValue() == true)
        {
            Page.Validate("cardetail");

            if (Page.IsValid)
            {
                if (Save())
                {
                    //BKICalculation();
                    lblMessage.Text = "Saved successfully!";
                    //_redirectUrl = CE.Global.General.GetUrl("~/car-insurance/profile.aspx", Page);
                    //Response.Redirect(_redirectUrl);

                    Int64 _userId = 0;
                    Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
                    bool _newuser = false;
                    if (Session[General.UserId] != null)
                    {
                        _userId = Convert.ToInt64(Session[General.UserId].ToString());
                    }
                    else
                    {
                        _newuser = true;
                    }

                    if (UpdateProfile(_userId, _carId) > 0)
                    {
                        //lblSortBy.Text = ddlSortBy.Text;
                        if (_newuser)
                        {
                            SendMailToUser(txtEmailAddress.Text.Trim(), Session[CE.Global.General.UserName].ToString(), txtMobileNo.GetPhoneNo());
                        }
                        //Response.Redirect("~/quote-results.aspx?sortby=" + lblSortBy.Text);
                        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/quote-results.aspx", Page);
                        Response.Redirect(_redirectUrl);
                    }
                }
                else
                {
                    lblMessage.Text = "Saving did NOT succeed!";
                }
            }
            else
            {
                lblMessage.Text = "Please fill all require fields completly and correctly.";
            }
        }
        else
        {
            lblMessage.Text = "Please fill claim value correctly.";
        }
    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("CI", Request, "Car Insurance car detail.");
    }

    private void CheckValidation()
    {
        Page.Validate();
    }

    private bool Save()
    {
        Int64 _carresult = 0;
        Int64 _policyresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        Int64 _refceuserid = 0;


        if (Session[General.CarId] != null)
        {
            //_car.CECarId = Convert.ToInt64(Session[General.CarId].ToString());
            _car = _cardb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), 0);
            if (Session[General.AgentId] != null)
            {
                _car.Info5 = "UPDATE";
            }
        }
        else
        {
            if (Session[General.AgentId] != null)
            {
                _car.Info4 = "NEW";
            }
        }
        if (Session[General.ViewedDetailsId] == null)
        {
            Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
        }

        if (_car == null)
        {
            _car = new CarDetailTH();
        }

        if (Session[CE.Global.General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[CE.Global.General.UserId]);
            _profile = _profiledb.GetProfile(_refceuserid);
            _contact = _contactdb.GetContact(_refceuserid);
            if (_profile != null && _contact != null)
            {
                _car.Info5 = _contact.Email;
                _car.Info6 = _contact.Mobile;
                _car.Info7 = _profile.SurName;
                if (_profile.FirstName.Trim().Length > 0)
                {
                    _car.Info8 = _profile.FirstName;//txtFirstName.Text.Trim();
                }
                _car.Info9 = _profile.Gender.ToString(); //ddlGender.GetGender();
                _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy"); //usrDOB.GetDate().ToString("dd-MMM-yyyy");
                _car.Info11 = _profile.Occupation.ToString();// ddlOccupation.GetOccupation();
                _car.Info12 = _profile.JobNature;//ddlJobNature.GetJobNature();
                _car.Info13 = _profile.MaritalStatus.ToString();//ddlMaritalStatus.GetMaritalStatus();
                _car.Info14 = "0"; //ddlYearDriveSg.Text;
                _car.Info15 = _profile.Salutation;//ddlSalutation.GetSalutation();
                _profile = null;
                _contact = null;
            }
        }



        _car.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);

        _car.CarMakeName = ddlCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);
        string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        _car.Info2 = lblCarVehicleType.Text;
        //LC = 210 or 220
        //PS = 110 or 120
        //PU = 320
        //SV = 110 or 120
        if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
        {
            _car.Info3 = ddlVehicleType.Text;
        }
        else if (lblCarVehicleType.Text == "LC")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "210";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "220";
            }
        }
        else if (lblCarVehicleType.Text == "PU")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "320";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "340"; //Disabled, No Packages
            }
        }
        //_car.Info3 = ddlVehicleType.Text;
        _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
        _car.Status = true;
        _car.RefCEUserId = _refceuserid;
        _car.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
        _car.CurrentStep = 1;
        _car.TotalStep = 4;

        //if (_refceuserid != 0)
        //{
        //    _profile = _profiledb.GetProfile(_refceuserid);
        //    if (_profile != null)
        //    {
        //        //Save User Profile
        //        _car.Info10 = _profile.SurName.ToString();
        //        _car.Info11 = _profile.Gender.ToString();
        //        _car.Info12 = _profile.DOB.ToString("dd-MMM-yyyy");
        //        _car.Info13 = _profile.Occupation.ToString();
        //        _car.Info14 = _profile.JobNature.ToString();
        //        _car.Info15 = _profile.MaritalStatus.ToString();
        //        _car.Info16 = _profile.YearDriveSg.ToString();
        //    }
        //}
        _car.Info1 = ddlCurInsuranceCompany.Text; //Current Insurer ID

        _carresult = _cardb.Insert(_car);

        _car = null;
        _cardb = null;
        //_profile = null;
        //_profiledb = null;

        if (_carresult > 0)
        {
            Session[CE.Global.General.CarId] = _carresult.ToString();
        }
        else
        {
            lblMessage.Text = "Insert error!";
        }
        //return _result > 0;
        if (_carresult > 0)
        {
            //CAR POLICY DETAILS
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());

            Int64 _carpolicyid = 0;

            if (Session[General.CarPolicyId] != null)
            {
                _carpolicyid = Convert.ToInt64(Session[General.CarPolicyId].ToString());
                _carpolicy.CECarPolicyId = _carpolicyid;
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info5 = "UPDATE";
                }
            }
            else
            {
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info4 = "NEW";
                }
            }

            lblMessage.Text = "";
            if (Session[General.AgentId] != null)
            {
                _carpolicy.Info2 = Session[General.AgentId].ToString();
                _carpolicy.Info3 = General.GetUTCDateTime().ToString();
            }
            _carpolicy.CECarId = _carId;
            _carpolicy.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
            _carpolicy.GarageType = Convert.ToInt32(ddlGarageType.Text);
            _carpolicy.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
            _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text);
            _carpolicy.ProvinceRegistration = ddlProvinceRegistration.Text;
            _carpolicy.UseOfVehicle = "N/A";//ddlUseOfVehicle.Text;
            string strDate = ddlCoverageComDate.Text;
            int _iDay = Convert.ToInt32(strDate.Substring(0, 2));
            int _iMonth = Convert.ToInt32(strDate.Substring(2, 2));
            int _iYear = Convert.ToInt32(strDate.Substring(4, 4));
            _carpolicy.CoverageCommenceDate = new DateTime(_iYear, _iMonth, _iDay);
            _carpolicy.IsRedPlate = false; //rdoYesRedPlate.Checked;

            _carpolicy.IsAddAccMod = rdoYesAccMod.Checked;

            if (rdoYesAccMod.Checked)
            {
                _carpolicy.AddAccModAmount = Convert.ToInt32(txtAccModAmount.Text);
            }
            else
            {
                _carpolicy.AddAccModAmount = 0;
            }
            _carpolicy.NCDPercent = Convert.ToInt32(ddlNCB.Text);
            //_carpolicy.NCDPercent = GetExistingNCD();

            //if (ddlNCB.Text == "60")
            //    _carpolicy.Info1 = "50";
            //else
            //    _carpolicy.Info1 = ddlNCB.Text;
            _carpolicy.IsClaimLastYear = rdoYesClaimLastYear.Checked;
            _carpolicy.IsCTPL = rdoYesCTPL.Checked;

            _carpolicy.IsAddDriver = rdoYesAddDriver.Checked;
            if (rdoYesAddDriver.Checked)
            {
                _carpolicy.NoOfDriver = Convert.ToInt16(ddlDriverCount.SelectedValue);
            }
            else
            {
                _carpolicy.NoOfDriver = 0;
            }
            _carpolicy.Deductible = rdoDeductNo.Checked == true ? 0 : 2000;
            _carpolicy.CurrentInsurer = ddlCurInsuranceCompany.SelectedItem.Text;
            _carpolicy.RefCEUserId = _refceuserid;
            _carpolicy.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
            _carpolicy.Status = true;
            _carpolicy.CurrentStep = 2;
            _policyresult = _carpolicydb.Insert(_carpolicy);
            if (_policyresult > 0)
            {
                Session[General.CarPolicyId] = _policyresult.ToString();
                #region No Claim History for Thailand 22/Feb/2011 Phyo
                //
                //if (_carpolicy.IsClaimLastThreeYear)
                //{
                //    CarClaimHistory _claimhis = new CarClaimHistory();
                //    CarClaimHistoryDB _claimhisdb = new CarClaimHistoryDB();

                //    if (Session[General.CarClaimHistoryId] != null)
                //    {
                //        _claimhis = _claimhisdb.GetCarClaimHistory(Convert.ToInt64(Session[General.CarClaimHistoryId]));
                //    }

                //    _claimhis.CECarId = _carId;
                //    _claimhis.RerCEUserId = _ceuserid;

                //    if (Convert.ToInt32(ddlNoOfClaim3.SelectedValue) > 0)
                //    {
                //        _claimhis.NoOfClaimInLast3Year = Convert.ToByte(ddlNoOfClaim3.SelectedValue);
                //        _claimhis.Last3YearClaimValue = txtClaimValue3.Text;
                //    }
                //    else
                //    {
                //        _claimhis.NoOfClaimInLast3Year = 0;
                //        _claimhis.Last3YearClaimValue = "0";
                //    }

                //    if (Convert.ToInt32(ddlNoOfClaim2.SelectedValue) > 0)
                //    {
                //        _claimhis.NoOfClaimInLast2Year = Convert.ToByte(ddlNoOfClaim2.SelectedValue);
                //        _claimhis.Last2YearClaimValue = txtClaimValue2.Text;
                //    }
                //    else
                //    {
                //        _claimhis.NoOfClaimInLast2Year = 0;
                //        _claimhis.Last2YearClaimValue = "0";
                //    }

                //    if (Convert.ToInt32(ddlNoOfClaim1.SelectedValue) > 0)
                //    {
                //        _claimhis.NoOfClaimInLast1Year = Convert.ToByte(ddlNoOfClaim1.SelectedValue);
                //        _claimhis.Last1YearClaimValue = txtClaimValue1.Text;
                //    }
                //    else
                //    {
                //        _claimhis.NoOfClaimInLast1Year = 0;
                //        _claimhis.Last1YearClaimValue = "0";
                //    }
                //    _claimhis.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
                //    _claimhis.Status = "Active";
                //    Int64 _resultclaimhis = _claimhisdb.Insert(_claimhis);
                //    if (_resultclaimhis > 0)
                //    {
                //        Session[General.CarClaimHistoryId] = _resultclaimhis.ToString();
                //        lblMessage.Text += "Car claim history saved successfully!";
                //    }
                //    else
                //    {
                //        lblMessage.Text += "Car claim history did not save successfully!";
                //    }
                //    _claimhis = null;
                //    _claimhisdb = null;
                //}
                //else
                //{
                //    if (Session[General.CarClaimHistoryId] != null)
                //    {
                //        CarClaimHistoryDB _carclaimdb = new CarClaimHistoryDB();
                //        if (_carclaimdb.UpdateStatus(Convert.ToInt64(Session[General.CarClaimHistoryId])))
                //        {

                //        }
                //    }
                //}
                #endregion
                lblMessage.Text += "<br>Car policy saved successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                lblMessage.Text = "Car policy did not save successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return false;
            }

            CarDriver _cardriver = new CarDriver();
            CarDriverDB _cardriverdb = new CarDriverDB();

            if (rdoYesAddDriver.Checked == true)
            {
                int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
                int _insertcount = 0;
                _cardriverdb.UpdateAllStatus(_carId, _refceuserid);

                for (int i = 1; i <= _drivercount; i++)
                {
                    _cardriver.StepId = 1;
                    _cardriver.RerCEUserId = _refceuserid;
                    _cardriver.CECarId = _carId;
                    if (i == 1)
                    {
                        UsrCarDriver1.SetProperty();
                        UsrCarDriver1.IsEnabled = true;
                        _cardriver.CarDriverId = UsrCarDriver1.DriverId;
                        _cardriver.DOB = UsrCarDriver1.DOB;
                        _cardriver.Status = "Active";
                    }
                    else if (i == 2)
                    {
                        UsrCarDriver2.SetProperty();
                        UsrCarDriver2.IsEnabled = true;
                        _cardriver.CarDriverId = UsrCarDriver2.DriverId;
                        _cardriver.DOB = UsrCarDriver2.DOB;
                        _cardriver.Status = "Active";
                    }

                    _cardriver.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
                    if (_cardriverdb.Insert(_cardriver) > 0)
                    {
                        _insertcount++;
                    }
                }

                _cardriverdb = null;
                _cardriver = null;

                if (_insertcount == _drivercount)
                {
                    lblMessage.Text += "<br>All drivers are successfully saved!";
                    lblMessage.ForeColor = System.Drawing.Color.Blue;
                }
                else
                {
                    lblMessage.Text += "<br>All drivers are did not saved!";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    return false;
                }
            }
            else
            {
                _cardriverdb.UpdateAllStatus(_carId, _refceuserid);
            }

            _carpolicy = null;
            _carpolicydb = null;
        }


        return _policyresult > 0;
    }

    private void GenerateServerSideCarModel(int CarMakeId)
    {
        CarDetailDB _cardeaildb = new CarDetailDB();
        Int64 _carmakecount = _cardeaildb.GetCarModelCount(CarMakeId);
        DataTable _dtCarModel = _cardeaildb.GetCarModel(CarMakeId);
        if (_dtCarModel != null)
        {
            if (_dtCarModel.Rows.Count > 0)
            {
                int _rowCount = _dtCarModel.Rows.Count;
                for (int i = 0; i < _rowCount; i++)
                {
                }
            }
        }
    }

    private void ChangeRequiredFieldValidation(WebControl ctl, RequiredFieldValidator rfv, string strValidation)
    {
        if (rfv.Enabled && rfv.ValidationGroup == strValidation)
        {
            rfv.Validate();
            if (rfv.IsValid == false)
            {
                ctl.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ctl.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ctl.ControlStyle.CssClass = "";
        }
    }
    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Insurance Type
        ChangeRequiredFieldValidation(ddlInsuranceType, rfvInsuranceType, strValidationGroup);
        //Garage Type
        ChangeRequiredFieldValidation(ddlGarageType, rfvGarageType, strValidationGroup);
        //Vehicle Type
        ChangeRequiredFieldValidation(ddlVehicleType, rfvVehicleType, strValidationGroup);
        //Year of Manufaturer
        ChangeRequiredFieldValidation(ddlManufactYear, rfvManufactYear, strValidationGroup);
        ChangeRequiredFieldValidation(ddlCarMake, rfvCarMake, strValidationGroup);
        ChangeRequiredFieldValidation(ddlModelBodyCCDoor, rfvModelBodyCCDoor, strValidationGroup);
        ChangeRequiredFieldValidation(txtSumInsured, rfvSumInsured, strValidationGroup);
        //rfvProvinceRegistration
        ChangeRequiredFieldValidation(ddlProvinceRegistration, rfvProvinceRegistration, strValidationGroup);

        //Any Claims?
        #region Any Claim
        if (rfvAnyClaim.Enabled && rfvAnyClaim.ValidationGroup == strValidationGroup)
        {
            rfvAnyClaim.Validate();
            if (rfvAnyClaim.IsValid == false)
            {
                lblYesClaimLastYear.ControlStyle.CssClass = "validationError";
                lblNoClaimLastYear.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesClaimLastYear.ControlStyle.CssClass = "";
                lblNoClaimLastYear.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesClaimLastYear.ControlStyle.CssClass = "";
            lblNoClaimLastYear.ControlStyle.CssClass = "";
        }
        #endregion
        //CTPL
        #region CTPL
        if (rfvCTPL.Enabled && rfvCTPL.ValidationGroup == strValidationGroup)
        {
            rfvCTPL.Validate();
            if (rfvCTPL.IsValid == false)
            {
                lblYesCTPL.ControlStyle.CssClass = "validationError";
                lblNoCTPL.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesCTPL.ControlStyle.CssClass = "";
                lblNoCTPL.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesCTPL.ControlStyle.CssClass = "";
            lblNoCTPL.ControlStyle.CssClass = "";
        }
        #endregion
        //Add Additional Name Driver
        #region Additional Name Driver
        if (rfvAddDriver.Enabled && rfvAddDriver.ValidationGroup == strValidationGroup)
        {
            rfvAddDriver.Validate();
            if (rfvAddDriver.IsValid == false)
            {
                lblYesAddDriver.ControlStyle.CssClass = "validationError";
                lblNoAddDriver.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesAddDriver.ControlStyle.CssClass = "";
                lblNoAddDriver.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesAddDriver.ControlStyle.CssClass = "";
            lblNoAddDriver.ControlStyle.CssClass = "";
        }
        #endregion

        //Cover Commencement Date
        ChangeRequiredFieldValidation(ddlCoverageComDate, rfvCoverComDate, strValidationGroup);
        //Current Insurance Company
        ChangeRequiredFieldValidation(ddlCurInsuranceCompany, rfvCurInsuranceCompany, strValidationGroup);

        //Car Driver
        UsrCarDriver1.ChangeValidationEffectServerSide("cardetail");
        UsrCarDriver2.ChangeValidationEffectServerSide("cardetail");


        //Profile
        ChangeRequiredFieldValidation(txtFirstName, rfvFirstName, strValidationGroup);
        ChangeRequiredFieldValidation(txtSurName, rfvSurName, strValidationGroup);
        if (revSurname.Enabled && revSurname.ValidationGroup == strValidationGroup)
        {
            revSurname.Validate();
            if (revSurname.IsValid == false)
            {
                txtSurName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtSurName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtSurName.ControlStyle.CssClass = "";
        }
        //Mobile No
        txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);
        //Date of birth
        usrDOB.ChangeValidationEffectServerSide(strValidationGroup);
        //Occupation
        ddlOccupation.ChangeValidationEffectServerSide(strValidationGroup);

        ChangeRequiredFieldValidation(txtConfirmEmailAddress, rfvConfirmEmail, strValidationGroup);

        if (cvConfirmEmail.Enabled && cvConfirmEmail.ValidationGroup == strValidationGroup && txtConfirmEmailAddress.Visible)
        {
            cvConfirmEmail.Validate();
            if (cvConfirmEmail.IsValid == false)
            {
                txtConfirmEmailAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtConfirmEmailAddress.ControlStyle.CssClass = "";
            }

        }
        else
        {
            txtConfirmEmailAddress.ControlStyle.CssClass = "";
        }
    }

    //CAR POLICY DETAILS
    #region No Claim History Details in Thailand Phyo
    //protected void CheckAllNoOfClaim(object source, ServerValidateEventArgs args)
    //{
    //    if (ddlNoOfClaim1.Text == "-1" && ddlNoOfClaim2.Text == "-1" && ddlNoOfClaim3.Text == "-1")
    //    {
    //        args.IsValid = false;
    //    }
    //    else
    //    {
    //        args.IsValid = true;
    //    }
    //}

    //protected void CheckClaimValue1(object source, ServerValidateEventArgs args)
    //{
    //    if (ddlNoOfClaim1.Text != "-1" && (Convert.ToInt32(txtClaimValue1.Text.Trim()) <= 0))
    //    {
    //        args.IsValid = false;
    //    }
    //    else
    //    {
    //        args.IsValid = true;
    //    }
    //}

    //protected void CheckClaimValue2(object source, ServerValidateEventArgs args)
    //{
    //    if (ddlNoOfClaim2.Text != "-1" && (Convert.ToInt32(txtClaimValue2.Text.Trim()) <= 0))
    //    {
    //        args.IsValid = false;
    //    }
    //    else
    //    {
    //        args.IsValid = true;
    //    }
    //}

    //protected void CheckClaimValue3(object source, ServerValidateEventArgs args)
    //{
    //    if (ddlNoOfClaim3.Text != "-1" && (Convert.ToInt32(txtClaimValue3.Text.Trim()) <= 0))
    //    {
    //        args.IsValid = false;
    //    }
    //    else
    //    {
    //        args.IsValid = true;
    //    }
    //}
    #endregion

    //protected void DriverFieldValidate(object source, ServerValidateEventArgs args)
    //{
    //    if (txtDriverValid.Text.ToLower() == "valid")
    //        args.IsValid = true;
    //    else
    //        args.IsValid = false;
    //}

    private void ShowCarAndPolicyDetail(Int64 CarId, Int64 PolicyId, Int64 UserId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        _cardetail = _cardetaildb.GetCar(CarId, UserId);

        CarPolicy _carpolicy = new CarPolicy();
        CarPolicyDB _carpolicydb = new CarPolicyDB();
        _carpolicy = _carpolicydb.GetCarPolicy(CarId, PolicyId, UserId);

        if (_carpolicy != null && _cardetail != null)
        {
            SetProperty(_carpolicy, _cardetail);
        }

        _cardetail = null;
        _cardetaildb = null;

        _carpolicy = null;
        _carpolicydb = null;
    }

    private void SetProperty(CarPolicy _CarPolicy, CarDetailTH _CarDetail)
    {
        ddlInsuranceType.Text = _CarPolicy.InsuranceType.ToString();
        ddlGarageType.Text = _CarPolicy.GarageType.ToString();
        LoadManufactYearList();

        ddlManufactYear.Text = _CarDetail.ManufactYear.ToString();
        ddlManufactYear_SelectedIndexChanged(null, null);
        ddlCarMake.Text = _CarDetail.CarMakeName;
        ddlCarMake_SelectedIndexChanged(null, null);
        string _tempDesc = _CarDetail.CarModelName + " " + _CarDetail.Body + " " + _CarDetail.CC + "cc " + _CarDetail.Door.ToString() + " doors";

        ddlModelBodyCCDoor.Text = _tempDesc;
        ddlModelBodyCCDoor_SelectedIndexChanged(null, null);
        ddlCurInsuranceCompany.Text = _CarDetail.Info1;
        txtGroupNo.Text = _CarDetail.GroupNo.ToString();
        lblCarVehicleType.Text = _CarDetail.Info2;
        //ChangeVehicleUsageList(lblCarVehicleType.Text);
        if (_CarDetail.Info3 == "110" || _CarDetail.Info3 == "210" || _CarDetail.Info3 == "320")
        {
            ddlVehicleType.Text = "110";
        }
        else
        {
            ddlVehicleType.Text = "120";
        }
        ddlVehicleType_SelectedIndexChanged(null, null);


        //ddlVehicleType.Text = _CarPolicy.VehicleType.ToString();
        //ddlVehicleType_SelectedIndexChanged(null, null);
        txtSumInsured.Text = _CarPolicy.SumInsured.ToString();
        lblSumInsured.Text = Convert.ToInt32(txtSumInsured.Text).ToString("#,000");

        rdoYesAccMod.Checked = _CarPolicy.IsAddAccMod;
        rdoNoAccMod.Checked = !_CarPolicy.IsAddAccMod;

        if (rdoYesAccMod.Checked)
        {
            txtNewSumInsured.Text = (_CarPolicy.SumInsured + _CarPolicy.AddAccModAmount).ToString();
            txtAccModAmount.Text = _CarPolicy.AddAccModAmount.ToString();
            lblSumInsured.Text = Convert.ToInt32(txtNewSumInsured.Text).ToString("#,000");
        }
        rdoDeductYes.Checked = _CarPolicy.Deductible > 0 ||_CarPolicy .Deductible == -1? true : false;
        rdoDeductNo.Checked = _CarPolicy.Deductible == 0 ? true : false;

        ddlProvinceRegistration.Text = _CarPolicy.ProvinceRegistration;
        //ddlUseOfVehicle.Text = _CarPolicy.UseOfVehicle;
        ddlCoverageComDate.Text = _CarPolicy.CoverageCommenceDate.Day.ToString("00") + _CarPolicy.CoverageCommenceDate.Month.ToString("00") + _CarPolicy.CoverageCommenceDate.Year.ToString("0000");
        DateTime _dtCommDate = _CarPolicy.CoverageCommenceDate;
        _dtCommDate = _dtCommDate.AddDays(-1);
        _dtCommDate = _dtCommDate.AddYears(1);
        lblCoverageExpireDate.Text = _dtCommDate.ToString("dd/MMMM/yyyy", CultureInfo.CurrentCulture);
        //rdoYesRedPlate.Checked = _CarPolicy.IsRedPlate;
        //rdoNoRedPlate.Checked = !_CarPolicy.IsRedPlate;
        rdoYesClaimLastYear.Checked = _CarPolicy.IsClaimLastYear;
        rdoNoClaimLastYear.Checked = !_CarPolicy.IsClaimLastYear;
        //if (rdoYesClaimLastYear.Checked)
        //{
        //    rdoYesCliam_CheckChange(null, null);
        //}
        //if (rdoNoClaimLastYear.Checked)
        //{
        //    rdoNoCliam_CheckChange(null, null);
        //}
        //Claim_Change(null, null);
        rdoYesAddDriver.Checked = false;    // _CarPolicy.IsAddDriver;
        rdoYesAddDriver_CheckedChanged(null, null);
        rdoNoAddDriver.Checked = true;  // !_CarPolicy.IsAddDriver;
        ddlDriverCount.Text = _CarPolicy.NoOfDriver.ToString();

        rdoYesCTPL.Checked = _CarPolicy.IsCTPL;
        rdoNoCTPL.Checked = !_CarPolicy.IsCTPL;
        //if (rdoYesClaimLastYear.Checked)
        //{
        //    CarClaimHistory _carclaimhistory = new CarClaimHistory();
        //    CarClaimHistoryDB _carclaimhistorydb = new CarClaimHistoryDB();
        //    _carclaimhistory = _carclaimhistorydb.GetCarClaimHistory(_CarPolicy.CECarId, _CarPolicy.RefCEUserId);
        //    if (_carclaimhistory != null)
        //    {
        //        Session[General.CarClaimHistoryId] = _carclaimhistory.CarClaimId.ToString();

        //        ddlNoOfClaim3.Text = _carclaimhistory.NoOfClaimInLast3Year.ToString();
        //        ddlNoOfClaim2.Text = _carclaimhistory.NoOfClaimInLast2Year.ToString();
        //        ddlNoOfClaim1.Text = _carclaimhistory.NoOfClaimInLast1Year.ToString();

        //        txtClaimValue3.Text = _carclaimhistory.Last3YearClaimValue.ToString();
        //        txtClaimValue2.Text = _carclaimhistory.Last2YearClaimValue.ToString();
        //        txtClaimValue1.Text = _carclaimhistory.Last1YearClaimValue.ToString();

        //        this.CheckClaim(this, null);
        //    }
        //}

        //if (_CarPolicy.NCDPercent == 50 && _CarPolicy.Info1 == "50")
        //    ddlNCB.Text = "60";
        //else
        //    ddlNCB.Text = _CarPolicy.Info1;
        ddlNCB.Text = _CarPolicy.NCDPercent.ToString();

        if (_CarPolicy.NoOfDriver > 0 && rdoYesAddDriver.Checked)
        {
            divAddDriver.Visible = true;
            pnlDriver.Visible = true;
            txtAddDriver.Text = "1";

            int _noOfDriver = _CarPolicy.NoOfDriver;
            CarDriverList _cardriverlist = new CarDriverList();
            CarDriverDB _cardriverdb = new CarDriverDB();
            _cardriverlist = _cardriverdb.GetCarDriverList(_CarPolicy.CECarId, _CarPolicy.RefCEUserId);
            _cardriverdb = null;

            for (int i = 1; i <= _noOfDriver; i++)
            {
                CarDriver _cardriver = _cardriverlist[i - 1];
                if (i == 1)
                {
                    UsrCarDriver1.DriverId = _cardriver.CarDriverId;
                    //UsrCarDriver1.Salutation = _cardriver.Salutation;
                    //UsrCarDriver1.SurName = Server.HtmlDecode(_cardriver.Surname);
                    //UsrCarDriver1.GivenName = Server.HtmlDecode(_cardriver.GivenName);
                    //UsrCarDriver1.Gender = _cardriver.Gender;
                    //UsrCarDriver1.MaritalStatus = _cardriver.MaritalStatus;
                    UsrCarDriver1.DOB = _cardriver.DOB;
                    //UsrCarDriver1.IDType = _cardriver.IDType;
                    //UsrCarDriver1.IDNo = _cardriver.IDNo;
                    //UsrCarDriver1.Occupation = _cardriver.Occupation;
                    //UsrCarDriver1.JobNature = _cardriver.JobNature;
                    //UsrCarDriver1.YearsOfDriving = _cardriver.YearOfDrivingInSg;
                    UsrCarDriver1.IsEnabled = true;
                    //UsrCarDriver1.SetProperty();
                }
                else if (i == 2)
                {
                    UsrCarDriver2.DriverId = _cardriver.CarDriverId;
                    //UsrCarDriver2.Salutation = _cardriver.Salutation;
                    //UsrCarDriver2.SurName = Server.HtmlDecode(_cardriver.Surname);
                    //UsrCarDriver2.GivenName = Server.HtmlDecode(_cardriver.GivenName);
                    //UsrCarDriver2.Gender = _cardriver.Gender;
                    //UsrCarDriver2.MaritalStatus = _cardriver.MaritalStatus;
                    UsrCarDriver2.DOB = _cardriver.DOB;
                    //UsrCarDriver2.IDType = _cardriver.IDType;
                    //UsrCarDriver2.IDNo = _cardriver.IDNo;
                    //UsrCarDriver2.Occupation = _cardriver.Occupation;
                    //UsrCarDriver2.JobNature = _cardriver.JobNature;
                    //UsrCarDriver2.YearsOfDriving = _cardriver.YearOfDrivingInSg;
                    UsrCarDriver2.IsEnabled = true;
                    //UsrCarDriver2.SetProperty();
                }
                #region Only two drivers details for thailand
                //else if (i == 3)
                //{
                //    UsrCarDriver3.DriverId = _cardriver.CarDriverId;
                //    //UsrCarDriver3.Salutation = _cardriver.Salutation;
                //    //UsrCarDriver3.SurName = Server.HtmlDecode(_cardriver.Surname);
                //    //UsrCarDriver3.GivenName = Server.HtmlDecode(_cardriver.GivenName);
                //    UsrCarDriver3.Gender = _cardriver.Gender;
                //    UsrCarDriver3.MaritalStatus = _cardriver.MaritalStatus;
                //    UsrCarDriver3.DOB = _cardriver.DOB;
                //    //UsrCarDriver3.IDType = _cardriver.IDType;
                //    //UsrCarDriver3.IDNo = _cardriver.IDNo;
                //    UsrCarDriver3.Occupation = _cardriver.Occupation;
                //    UsrCarDriver3.JobNature = _cardriver.JobNature;
                //    UsrCarDriver3.YearsOfDriving = _cardriver.YearOfDrivingInSg;
                //    UsrCarDriver3.IsEnabled = true;
                //    //UsrCarDriver3.SetProperty();
                //}
                //else if (i == 4)
                //{
                //    UsrCarDriver4.DriverId = _cardriver.CarDriverId;
                //    //UsrCarDriver4.Salutation = _cardriver.Salutation;
                //    //UsrCarDriver4.SurName = Server.HtmlDecode(_cardriver.Surname);
                //    //UsrCarDriver4.GivenName = Server.HtmlDecode(_cardriver.GivenName);
                //    UsrCarDriver4.Gender = _cardriver.Gender;
                //    UsrCarDriver4.MaritalStatus = _cardriver.MaritalStatus;
                //    UsrCarDriver4.DOB = _cardriver.DOB;
                //    //UsrCarDriver4.IDType = _cardriver.IDType;
                //    //UsrCarDriver4.IDNo = _cardriver.IDNo;
                //    UsrCarDriver4.Occupation = _cardriver.Occupation;
                //    UsrCarDriver4.JobNature = _cardriver.JobNature;
                //    UsrCarDriver4.YearsOfDriving = _cardriver.YearOfDrivingInSg;
                //    UsrCarDriver4.IsEnabled = true;
                //    //UsrCarDriver4.SetProperty();
                //}
                //else if (i == 5)
                //{
                //    UsrCarDriver5.DriverId = _cardriver.CarDriverId;
                //    //UsrCarDriver5.Salutation = _cardriver.Salutation;
                //    //UsrCarDriver5.SurName = Server.HtmlDecode(_cardriver.Surname);
                //    //UsrCarDriver5.GivenName = Server.HtmlDecode(_cardriver.GivenName);
                //    UsrCarDriver5.Gender = _cardriver.Gender;
                //    UsrCarDriver5.MaritalStatus = _cardriver.MaritalStatus;
                //    UsrCarDriver5.DOB = _cardriver.DOB;
                //    //UsrCarDriver5.IDType = _cardriver.IDType;
                //    //UsrCarDriver5.IDNo = _cardriver.IDNo;
                //    UsrCarDriver5.Occupation = _cardriver.Occupation;
                //    UsrCarDriver5.JobNature = _cardriver.JobNature;
                //    UsrCarDriver5.YearsOfDriving = _cardriver.YearOfDrivingInSg;
                //    UsrCarDriver5.IsEnabled = true;
                //    //UsrCarDriver5.SetProperty();
                //}
                #endregion
            }
            _cardriverlist = null;
        }
        else
        {
            pnlDriver.Visible = false;
            divAddDriver.Visible = false;
            txtAddDriver.Text = "1";
        }
    }

    private void DriverSetting()
    {
        //if (ddlDriverCount.SelectedValue != "-1" && rdoYesAddDriver.Checked)
        if (rdoYesAddDriver.Checked)
        {
            int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
            //Only Class1 has Named driver
            
            //Only two drivers for thailand Phyo
            for (int i = 1; i <= 2; i++)
            {
                string strDivName = "divDriver" + i.ToString();
                HtmlGenericControl _divDriver = (HtmlGenericControl)pnlDriver.FindControl(strDivName);
                //string strUsrDriver = "UsrCarDriver" + i.ToString();
                //controls_usrCarDriverDetails _ctrlDriver = (controls_usrCarDriverDetails)pnlDriver.FindControl(strUsrDriver);
                if (i > _drivercount)
                {
                    if (_divDriver != null)
                    {
                        _divDriver.Visible = false;
                        //_ctrlDriver.Visible = false;
                    }
                }
                else
                {
                    if (_divDriver != null)
                    {
                        _divDriver.Visible = true;
                        //_ctrlDriver.Visible = true;
                    }
                }
            }
        }
        else
        {
            for (int i = 1; i <= 2; i++)
            {
                string strDivName = "divDriver" + i.ToString();
                HtmlGenericControl _divDriver = (HtmlGenericControl)pnlDriver.FindControl(strDivName);
                string strUsrDriver = "UsrCarDriver" + i.ToString();
                controls_usrCarDriverDetails _ctrlDriver = (controls_usrCarDriverDetails)pnlDriver.FindControl(strUsrDriver);
                if (_divDriver != null && _ctrlDriver != null)
                {
                    _divDriver.Visible = false;
                    _ctrlDriver.ClearProperty();
                    _ctrlDriver.IsEnableValidation(false);
                }

            }
        }



         
    }

    private void OtherValidation()
    {
        if (rdoYesClaimLastYear.Checked == false && rdoNoClaimLastYear.Checked == false)
        {
            rfvAnyClaim.IsValid = false;
        }
        else
        {
            txtAnyClaim.Text = "1";
            rfvAnyClaim.Validate();
        }

        if (rdoYesAccMod.Checked == false && rdoNoAccMod.Checked == false)
        {
            rfvAccMod.IsValid = false;
        }
        else
        {
            if (rdoYesAccMod.Checked)
            {
                rfvAccModAmount.Validate();
                revAccModAmount.Validate();
                csvAccModAmount.Validate();
            }
            else
            {
                rfvAccModAmount.Enabled = false;
                revAccModAmount.Enabled = false;
                csvAccModAmount.Enabled = false;
                txtAccModAmount.Text = "0";
            }
            txtAccMod.Text = "1";
            rfvAccMod.Validate();
        }

        #region No Claim History for thailand
        //if (rdoYesClaimLast3Year.Checked)
        //{
        //    divAnyClaim.Style.Value = ""; ;

        //    rfvNoOfClaim3.Enabled = true;
        //    rfvNoOfClaim2.Enabled = true; /// NO NEED
        //    rfvNoOfClaim1.Enabled = true; /// NO NEED
        //    csvNoOfClaimAll.Enabled = true;                               /// 
        //    if (Convert.ToInt32(ddlNoOfClaim3.SelectedValue) > 0)
        //    {
        //        rfvClaimValue3.Enabled = true;
        //        revClaimValue3.Enabled = true;
        //    }
        //    else
        //    {
        //        rfvClaimValue3.Enabled = false;
        //        revClaimValue3.Enabled = false;
        //    }

        //    if (Convert.ToInt32(ddlNoOfClaim2.SelectedValue) > 0)
        //    {
        //        rfvClaimValue2.Enabled = true;
        //        revClaimValue2.Enabled = true;
        //    }
        //    else
        //    {
        //        rfvClaimValue2.Enabled = false;
        //        revClaimValue2.Enabled = false;
        //    }

        //    if (Convert.ToInt32(ddlNoOfClaim1.SelectedValue) > 0)
        //    {
        //        rfvClaimValue1.Enabled = true;
        //        revClaimValue1.Enabled = true;
        //    }
        //    else
        //    {
        //        rfvClaimValue1.Enabled = false;
        //        revClaimValue1.Enabled = false;
        //    }

        //    if (Convert.ToInt32(ddlNoOfClaim1.SelectedValue) > 0 ||
        //       Convert.ToInt32(ddlNoOfClaim2.SelectedValue) > 0 ||
        //        Convert.ToInt32(ddlNoOfClaim3.SelectedValue) > 0)
        //    {
        //        if (Convert.ToInt32(ddlNoOfClaim1.SelectedValue) < 0)
        //        {
        //            ddlNoOfClaim1.Text = "-1";
        //            //ddlClaimValue1.Text = "-1";
        //            txtClaimValue1.Text = "";
        //            rfvNoOfClaim1.Enabled = false;
        //            rfvClaimValue1.Enabled = false;
        //            revClaimValue1.Enabled = false;

        //        }

        //        if (Convert.ToInt32(ddlNoOfClaim2.SelectedValue) < 0)
        //        {
        //            ddlNoOfClaim2.Text = "-1";
        //            //ddlClaimValue2.Text = "-1";
        //            txtClaimValue2.Text = "";
        //            rfvNoOfClaim2.Enabled = false;
        //            rfvClaimValue2.Enabled = false;
        //            revClaimValue2.Enabled = false;
        //        }

        //        if (Convert.ToInt32(ddlNoOfClaim3.SelectedValue) < 0)
        //        {
        //            ddlNoOfClaim3.Text = "-1";
        //            //ddlClaimValue3.Text = "-1";
        //            txtClaimValue3.Text = "";
        //            rfvNoOfClaim3.Enabled = false;
        //            rfvClaimValue3.Enabled = false;
        //            revClaimValue3.Enabled = false;
        //        }
        //    }

        //}
        //else
        //{
        //    //divAddDriver.Style.Value = "display:none"; ;
        //    csvNoOfClaimAll.Enabled = false;
        //    rfvNoOfClaim3.Enabled = false;
        //    rfvClaimValue3.Enabled = false;
        //    revClaimValue3.Enabled = false;
        //    rfvClaimValue2.Enabled = false;
        //    revClaimValue2.Enabled = false;
        //    rfvClaimValue1.Enabled = false;
        //    revClaimValue1.Enabled = false;
        //    rfvNoOfClaim2.Enabled = false;
        //    rfvNoOfClaim1.Enabled = false;
        //}
        #endregion
    }

    private bool DriverValidation()
    {
        //String[] ArrDriver;
        //bool _result = true;
        //lblMessage.Text = "";
        //if (ddlDriverCount.SelectedValue != "-1")
        //{
        //    int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
        //    divAddDriver.Visible = false;

        //    ArrDriver = new String[_drivercount + 1];
        //    for (int i = 1; i <= 5; i++)
        //    {
        //        string strCtrlName = "UsrCarDriver" + i.ToString();
        //        string strDivDriverName = "divDriver" + i.ToString();
        //        controls_usrCarDriverDetails ctrlDriver = (controls_usrCarDriverDetails)pnlDriver.FindControl(strCtrlName);
        //        HtmlGenericControl divCtrl = (HtmlGenericControl)pnlDriver.FindControl(strDivDriverName);
        //        if (divCtrl != null)
        //        {
        //            divCtrl.Visible = false;
        //        }

        //        if (ctrlDriver != null)
        //        {
        //            ctrlDriver.IsEnableValidation(false);
        //        }
        //        if (i <= _drivercount)
        //        {
        //            ArrDriver[i] = "";
        //        }
        //    }

        //    if (rdoYesAddDriver.Checked)
        //    {
        //        divAddDriver.Style.Value = ""; ;
        //        ddlDriverCount.Enabled = true;
        //        for (int i = _drivercount; i >= 1; i--)
        //        {
        //            string strCtrlName = "UsrCarDriver" + i.ToString();
        //            string strDivDriverName = "divDriver" + i.ToString();
        //            controls_usrCarDriverDetails ctrlDriver = (controls_usrCarDriverDetails)pnlDriver.FindControl(strCtrlName);
        //            HtmlGenericControl divCtrl = (HtmlGenericControl)pnlDriver.FindControl(strDivDriverName);
        //            if (divCtrl != null)
        //            {
        //                divCtrl.Visible = true;
        //            }

        //            if (ctrlDriver != null)
        //            {

        //                ctrlDriver.IsEnableValidation(true);

        //                ctrlDriver.ClearProperty();
        //                ctrlDriver.SetProperty();

        //            }
        //        }


        //        for (int i = 1; i <= _drivercount; i++)
        //        {
        //            string IdNo = "";
        //            IdNo = ArrDriver[i].ToString();
        //            if (IdNo.Length < 9) continue;

        //            for (int j = _drivercount; j > i; j--)
        //            {
        //                if (IdNo == ArrDriver[j])
        //                {
        //                    if (j == _drivercount && i == 1 && csvDriver.ErrorMessage.Length == 0)
        //                    {
        //                        csvDriver.ErrorMessage += "Driver " + i.ToString() + "'s ID Number should not same with Driver " + j.ToString() + "'s ID Number.";
        //                    }
        //                    else
        //                    {
        //                        csvDriver.ErrorMessage += "<li>Driver " + i.ToString() + "'s ID Number should not same with Driver " + j.ToString() + "'s ID Number.</li>";
        //                    }
        //                    //lblMessage.Text += "Driver " + (i + 1).ToString() + "'s ID Number should not same with Driver  " + (j + 1).ToString() + "'s ID Number.<br/>";
        //                    _result = false;
        //                }
        //            }
        //        }
        //    }

        //}
        //return _result;
        return true;
    }

    private bool CheckClaimValue()
    {
        bool ClaimValue = true;
        //if (rdoYesClaimLast3Year.Checked == true)
        //{
        //    if ((ddlNoOfClaim3.SelectedIndex > 0) && (Convert.ToInt32(txtClaimValue3.Text.Trim()) <= 0))
        //    {
        //        ClaimValue = false;
        //    }
        //    else if ((ddlNoOfClaim2.SelectedIndex > 0) && (Convert.ToInt32(txtClaimValue2.Text.Trim()) <= 0))
        //    {
        //        ClaimValue = false;
        //    }
        //    else if ((ddlNoOfClaim1.SelectedIndex > 0) && (Convert.ToInt32(txtClaimValue1.Text.Trim()) <= 0))
        //    {
        //        ClaimValue = false;
        //    }
        //}
        return ClaimValue;
    }

    private int GetExistingNCD()
    {
        int ExistingNCD = 0;

        if (ddlNCB.Text == "0")
            ExistingNCD = -1;
        else
            ExistingNCD = Convert.ToInt32(ddlNCB.Text) - 10;
        return ExistingNCD;
    }

    protected void rdoYesAddDriver_CheckedChanged(object sender, EventArgs e)
    {
        //Claim_Change(sender, e);
        if (rdoYesAddDriver.Checked)
        {
            rdoNoAddDriver.Checked = false;
            txtAddDriver.Text = "1";
            pnlDriver.Visible =  true;
            divAddDriver.Visible = true;
            ddlDriverCount.Text = "1";

            DriverSetting();
        }
    }

    protected void rdoNoAddDriver_CheckedChanged(object sender, EventArgs e)
    {
        //Claim_Change(sender, e);
        if (rdoNoAddDriver.Checked)
        {
            rdoYesAddDriver.Checked = false;
            txtAddDriver.Text = "1";
            pnlDriver.Visible = false;
            divAddDriver.Visible = false;

            DriverSetting();

        }

    }

    protected void rdoNoCliam_CheckChange(object sender, EventArgs e)
    {
        //Claim_Change(sender, e);
        txtAnyClaim.Text = "1";
        ddlNCB.Items.Clear();
        ddlNCB.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlNCB.Items.Add(new ListItem("0 %", "0"));
        //ddlNCB.Items.Add(new ListItem("10", "10"));
        ddlNCB.Items.Add(new ListItem("20 %", "20"));
        ddlNCB.Items.Add(new ListItem("30 %", "30"));
        ddlNCB.Items.Add(new ListItem("40 %", "40"));
        ddlNCB.Items.Add(new ListItem("50 %", "50"));
        //divNCB.Visible = true;
    }

    //protected void rdoYesCliam_CheckChange(object sender, EventArgs e)
    //{
    //    //Claim_Change(sender, e);
    //    //ddlNCB.Items.Clear();
    //    //txtAnyClaim.Text = "1";
    //    //ddlNCB.Items.Add(new ListItem("0", "0"));
    //    //divNCB.Visible = false;
    //}

    #region Claim Change Function No Need for thailand
    //protected void Claim_Change(object sender, EventArgs e)
    //{
    //    if (rdoYesClaimLast3Year.Checked == false)
    //    {
    //        divAnyClaim.Visible = false;
    //        txtAnyClaim.Text = "1";
    //        rfvNoOfClaim1.Enabled = false;
    //        rfvNoOfClaim2.Enabled = false;
    //        rfvNoOfClaim3.Enabled = false;

    //        rfvClaimValue1.Enabled = false;
    //        rfvClaimValue2.Enabled = false;
    //        rfvClaimValue3.Enabled = false;

    //        revClaimValue1.Enabled = false;
    //        revClaimValue2.Enabled = false;
    //        revClaimValue3.Enabled = false;

    //        ddlNoOfClaim1.Text = "-1";
    //        ddlNoOfClaim2.Text = "-1";
    //        ddlNoOfClaim3.Text = "-1";
    //        txtClaimValue1.Text = "";
    //        txtClaimValue2.Text = "";
    //        txtClaimValue3.Text = "";
    //    }
    //    else if (rdoYesClaimLast3Year.Checked == true)
    //    {
    //        divAnyClaim.Visible = true;
    //        txtAnyClaim.Text = "1";
    //        rfvNoOfClaim1.Enabled = true;
    //        rfvNoOfClaim2.Enabled = true;
    //        rfvNoOfClaim3.Enabled = true;

    //        rfvClaimValue1.Enabled = true;
    //        rfvClaimValue2.Enabled = true;
    //        rfvClaimValue3.Enabled = true;

    //        revClaimValue1.Enabled = true;
    //        revClaimValue2.Enabled = true;
    //        revClaimValue3.Enabled = true;
    //    }
    //}

    //protected void ddlNCD_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    divNCDYear.Visible = false;
    //    ddlNCB.Enabled = true;
    //    ddlNCB.Items.Clear();
    //    int _curNCD = Convert.ToInt32(ddlNCD.Text);

    //    if (_curNCD == -1)
    //    {
    //        rdoYesClaimLast3Year.Checked = false;
    //        rdoNoClaimLast3Year.Checked = true;
    //    }

    //    if (rdoYesClaimLast3Year.Checked == false)
    //    {
    //        if (_curNCD == -1)
    //        {
    //            ddlNCB.Items.Add(new ListItem("0", "0"));
    //        }
    //        else if (_curNCD == 0)
    //        {
    //            ddlNCB.Items.Add(new ListItem("0", "0"));
    //            ddlNCB.Items.Add(new ListItem("10", "10"));
    //            ddlNCB.Text = "10";
    //        }
    //        else if (_curNCD == 10)
    //        {
    //            ddlNCB.Items.Add(new ListItem("10", "10"));
    //            ddlNCB.Items.Add(new ListItem("20", "20"));
    //            ddlNCB.Text = "20";
    //        }
    //        else if (_curNCD == 20)
    //        {
    //            ddlNCB.Items.Add(new ListItem("20", "20"));
    //            ddlNCB.Items.Add(new ListItem("30", "30"));
    //            ddlNCB.Text = "30";
    //        }
    //        else if (_curNCD == 30)
    //        {
    //            ddlNCB.Items.Add(new ListItem("30", "30"));
    //            ddlNCB.Items.Add(new ListItem("40", "40"));
    //            ddlNCB.Text = "40";
    //        }
    //        else if (_curNCD == 40)
    //        {
    //            ddlNCB.Items.Add(new ListItem("40", "40"));
    //            ddlNCB.Items.Add(new ListItem("50", "50"));
    //            ddlNCB.Text = "50";

    //            divNCDYear.Visible = true;
    //        }
    //        else if (_curNCD == 50)
    //        {
    //            ddlNCB.Items.Add(new ListItem("50", "50"));
    //            ddlNCB.Text = "50";

    //           divNCDYear.Visible = true;
    //        }
    //        divAnyClaim.Visible = false;
    //        txtAnyClaim.Text = "1";
    //        rfvNoOfClaim1.Enabled = false;
    //        rfvNoOfClaim2.Enabled = false;
    //        rfvNoOfClaim3.Enabled = false;

    //        rfvClaimValue1.Enabled = false;
    //        rfvClaimValue2.Enabled = false;
    //        rfvClaimValue3.Enabled = false;

    //        revClaimValue1.Enabled = false;
    //        revClaimValue2.Enabled = false;
    //        revClaimValue3.Enabled = false;
    //    }
    //    else
    //    {
    //        divAnyClaim.Visible = true;
    //        txtAnyClaim.Text = "1";
    //        rfvNoOfClaim1.Enabled = true;
    //        rfvNoOfClaim2.Enabled = true;
    //        rfvNoOfClaim3.Enabled = true;

    //        rfvClaimValue1.Enabled = true;
    //        rfvClaimValue2.Enabled = true;
    //        rfvClaimValue3.Enabled = true;

    //        revClaimValue1.Enabled = true;
    //        revClaimValue2.Enabled = true;
    //        revClaimValue3.Enabled = true;

    //        ddlNCB.Items.Add(new ListItem("0", "0"));
    //        ddlNCB.Items.Add(new ListItem("10", "10"));
    //        ddlNCB.Items.Add(new ListItem("20", "20"));
    //        ddlNCB.Items.Add(new ListItem("30", "30"));
    //        ddlNCB.Items.Add(new ListItem("40", "40"));
    //        ddlNCB.Items.Add(new ListItem("50", "50"));
    //    }
    //}

    //protected void ddlNCB_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    if (ddlNCB.Text == "50")
    //    {
    //        divNCDYear.Visible = true;
    //    }
    //    else
    //    {
    //        divNCDYear.Visible = false;
    //    }
    //}
    #endregion

    protected void CheckClaim(object sender, EventArgs e)
    {
        ddlNCB.Items.Clear();
        ddlNCB.Items.Add(new ListItem("No NCD", "0"));
        //if (ddlNoOfClaim1.Text == "1")
        //{
        //    ddlNCB.Items.Add(new ListItem("0", "0"));
        //    ddlNCB.Items.Add(new ListItem("10", "10"));
        //    ddlNCB.Items.Add(new ListItem("20", "20"));
        //}
        //else if (ddlNoOfClaim1.Text == "-1")
        //{
        //    if (ddlNoOfClaim2.Text == "1")
        //    {
        //        ddlNCB.Items.Add(new ListItem("0", "0"));
        //        ddlNCB.Items.Add(new ListItem("10", "10"));
        //        ddlNCB.Items.Add(new ListItem("20", "20"));
        //        ddlNCB.Items.Add(new ListItem("30", "30"));
        //    }
        //    else if (ddlNoOfClaim2.Text == "-1")
        //    {
        //        if (ddlNoOfClaim3.Text == "1")
        //        {
        //            ddlNCB.Items.Add(new ListItem("0", "0"));
        //            ddlNCB.Items.Add(new ListItem("10", "10"));
        //            ddlNCB.Items.Add(new ListItem("20", "20"));
        //            ddlNCB.Items.Add(new ListItem("30", "30"));
        //            ddlNCB.Items.Add(new ListItem("40", "40"));
        //        }
        //        else if (ddlNoOfClaim3.Text == "-1")
        //        {
        //            ddlNCB.Items.Add(new ListItem("0", "0"));
        //            ddlNCB.Items.Add(new ListItem("10", "10"));
        //            ddlNCB.Items.Add(new ListItem("20", "20"));
        //            ddlNCB.Items.Add(new ListItem("30", "30"));
        //            ddlNCB.Items.Add(new ListItem("40", "40"));
        //            ddlNCB.Items.Add(new ListItem("50% (1st year)", "50"));
        //            ddlNCB.Items.Add(new ListItem("50% (> one year)", "60"));
        //        }
        //        else
        //        {
        //            ddlNCB.Items.Add(new ListItem("0", "0"));
        //            ddlNCB.Items.Add(new ListItem("10", "10"));
        //            ddlNCB.Items.Add(new ListItem("20", "20"));
        //        }

        //    }
        //    else
        //    {
        //        ddlNCB.Items.Add(new ListItem("0", "0"));
        //        ddlNCB.Items.Add(new ListItem("10", "10"));
        //    }

        //}
        //else
        //{
        //    ddlNCB.Items.Add(new ListItem("0", "0"));

        //}
    }

    protected void ddlDriverCount_SelectedIndexChanged(object sender, EventArgs e)
    {
        DriverSetting();
    }

    private bool CheckFirstTimeQuote()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocAutoEmailFirstQuoteInsertUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@RefCEUserId", Session[General.UserId].ToString());
        _spList.Add("@EmailType", 100);
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);
        return _retValue == 1;
    }

    private bool SendMailFirstQuoteToUser()
    {
        bool _retVal = false;
        //MyMailManager _mailMgr = new MyMailManager();
        string _emailTo = Session[CE.Global.General.UserEmail].ToString();
        string _customername = Session[CE.Global.General.UserName].ToString();
        string _emailSubject = "First Car Insurance Quote - " + General.GetUTCDateTime().ToString();
        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");
        CompanyInformation _company = new CompanyInformation();
        CompanyInformationDB _companydb = new CompanyInformationDB();
        _company = _companydb.GetCompanyInformation(3);
        string _companyAddress = "";
        string _emailaddress = "";
        string _websiteaddress = "";
        if (_company != null)
        {
            _companyAddress = _company.Address1;
            _emailaddress = _company.EmailAddress;
            _websiteaddress = _company.Website;
        }
        _company = null;
        _companydb = null;

        _mailBody = "Dear " + _customername + ", <br /><br />Thank you for using <a href='http://www.gluaygluay.com' target='_blank'>www.gluaygluay.com</a> for the first time.";
        _mailBody += "<br /><br />You are able to view this quote through our Members Area by clicking on the link below. <br /><br /> <a href='http://www.comparexpress.com' target='_blank'>http://www.gluaygluay.com</a>.";
        _mailBody += "<br /><br /> Enter your Email and Password to login to the Members Area, located on the top right of the page.";
        _mailBody += "<br /><br />If you have any questions, comments, or feedback, please do not hesitate to contact us at <a href='mailto:support@gluaygluay.com'>support@gluaygluay.com</a>.";
        _mailBody += "<br /><br />Best Regards,<br /><br />Your <a href='http://www.gluaygluay.com' target='_blank'>www.gluaygluay.com</a> Team<br/>Customer Support";
        _mailBody += "<br /><img src='" + imgLogoUrl + "' />";
        _mailBody += "<br /><hr />";
        _mailBody += _companyAddress;
        _mailBody += "<br /><a href='" + _websiteaddress + "' target='_blank'>" + _websiteaddress + "</a> :: <a href='mailto:" + _emailaddress + "' target='_blank'>" + _emailaddress + "</a><br /><hr />";
        _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";
        if (MyMailManager.SendCRMMessage(_emailTo, _emailSubject, _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        //System.Threading.Thread.Sleep(10000);
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

            txtSumInsured.Text = "0";
            lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlManufactYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }
        }
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        txtSumInsured.Text = "0";
        lblSumInsured.Text = "0";
        txtGroupNo.Text = "-1";
    }

    protected void ddlManufactYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.Text == "-1")
        {
            ClearAllList();
        }
        else
        {
            GetCarMakeList(ddlManufactYear.Text, ddlCarMake);
            if (ddlCarMake.Items.Count > 0)
            {
                ddlCarMake.SelectedIndex = 0;
                ddlCarMake_SelectedIndexChanged(sender, e);
            }
        }
    }


    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlManufactYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            if (rdoYesAccMod.Checked)
            {
                if (txtAccModAmount.Text.Length > 0)
                {
                    int _sumInsured = Convert.ToInt32(txtSumInsured.Text);
                    int _tmpAmount = 0;
                    if (Int32.TryParse(txtAccModAmount.Text, out _tmpAmount))
                    {
                        _sumInsured += _tmpAmount;
                        txtNewSumInsured.Text = _sumInsured.ToString();
                        lblSumInsured.Text = Convert.ToInt32(txtNewSumInsured.Text).ToString("#,000");
                    }
                    else
                    {
                        txtNewSumInsured.Text = _sumInsured.ToString();
                        txtAccModAmount.Text = "";
                    }
                }
            }
            //ChangeVehicleUsageList(lblCarVehicleType.Text);
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
            //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Init_JTip_Driver", "JT_init();", true);
            //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ShowHide_AccMod", "CheckAccMod();", true);
            //CheckAccMod()
        }
    }

    private void ChangeVehicleUsageList(string CarVehicleType)
    {
        //<asp:ListItem Value="110" Text="<%$ Resources:CarInsurance,VehicleType_Private%>" />
        //<asp:ListItem Value="120" Text="<%$ Resources:CarInsurance,VehicleType_Commercial%>" />
        //int _selectetIndex = ddlVehicleType.SelectedIndex;
        ddlVehicleType.Items.Clear();
        ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (CarVehicleType == "PU")
        {
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
            //if (_selectetIndex == 1)
            //    ddlVehicleType.SelectedIndex = 1;
            //else
            //    ddlVehicleType.SelectedIndex = 0;
            //ddlVehicleType_SelectedIndexChanged(null, null);
        }
        else
        {
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Commercial, "120"));
            //ddlVehicleType.SelectedIndex = _selectetIndex;
            //ddlVehicleType_SelectedIndexChanged(null, null);
        }
        rdoNoAddDriver.Checked = false;
        rdoYesAddDriver.Checked = false;
        divSpecifyDriver.Visible = false;
        divAddDriver.Visible = false;
    }
    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        //ddlCarMake.Items.Add(new ListItem("Test", "TEST"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelDescTHListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][0].ToString()));
            }
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        _dt = null;
        _db = null;
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
            //txtTextBox.Text = string.Format("{0:#,0}", _dt.Rows[0][0]);
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    protected void ddlInsuranceType_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (Convert.ToInt32(ddlInsuranceType.Text) >= 20)
            {
                lblSumInsured.Visible = false;
                lblSumInsuredTitle.Visible = false;
                rfvSumInsured.Enabled = false;
                txtSumInsured.Enabled = false;
            }
            else
            {
                lblSumInsured.Visible = false; //true;
                lblSumInsuredTitle.Visible = false; //true;
                rfvSumInsured.Enabled = true;
                txtSumInsured.Enabled = true;
            }
            LoadManufactYearList();
            ClearAllList();
        }
        catch
        {

        }
    }

    private void LoadManufactYearList()
    {
        int _yearCount = 10;
        ddlManufactYear.Items.Clear();

        if (ddlInsuranceType.Text != "-1")
        {
            if (Convert.ToInt32(ddlInsuranceType.Text) >= 20)
            {
                _yearCount = 20;
            }
            int _startYear = General.GetUTCDateTime().Year - _yearCount;
            int _endYear = General.GetUTCDateTime().Year;
            for (int i = _endYear; i >= _startYear; i--)
            {
                //ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                if (CultureInfo.CurrentCulture.Name != "th-TH")
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                else
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
                }
            }
        }
        ddlManufactYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlVehicleType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVehicleType.Text == "110")
        {
            if (lblCarVehicleType.Text == "PU")
            {
                //if (ddlVehicleType.Text == "110")
                //{
                //    _car.Info3 = "320";
                //}
                //else if (ddlVehicleType.Text == "120")
                //{
                //    _car.Info3 = "340"; //Disabled, No Packages
                //}
                divSpecifyDriver.Visible = false;
            }
            else
            {
                //divSpecifyDriver.Visible = true;
                divSpecifyDriver.Visible = false;
            }
            //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Init_JTip_Driver", "JT_init();", true);
        }
        else
        {
            divSpecifyDriver.Visible = false;
            rdoNoAddDriver.Checked = true;
            rdoNoAddDriver_CheckedChanged(sender, e);
        }

    }

    protected void CheckAccModAmount(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = true;
    }

    #region Profile Page

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();

            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; // ddlSalutation.GetSalutation();
                _profile.FirstName = txtFirstName.Text;
                _profile.SurName = txtSurName.Text;
                _profile.DOB = usrDOB.GetDate();
                _profile.Gender = Convert.ToChar(ddlGender.GetGender());

                _profile.MaritalStatus = -1;// Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                _profile.JobNature = "";// ddlJobNature.GetJobNature();
                _profile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                _profile.YearDriveSg = 0;//Convert.ToInt16(ddlYearDriveSg.Text);
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobileNo.GetPhoneNo();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                    //divNewErrorMessage.Visible = true;
                    //lblCarInsProfileMessage.Text = "Error found in profile update!";
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[General.UserPhoneNo] = txtMobileNo.GetPhoneNo();
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }
                else
                {
                    //divNewErrorMessage.Visible = true;
                    //lblCarInsProfileMessage.Text = "Error found in contact update!";
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        if (_retValue > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = txtEmailAddress.Text;
                _cardetail.Info6 = txtMobileNo.GetPhoneNo();
                _cardetail.Info7 = txtSurName.Text.Trim();
                if (txtFirstName.Text.Trim().Length > 0)
                {
                    _cardetail.Info8 = txtFirstName.Text.Trim();
                }
                //CultureInfo ci = CultureInfo.CurrentCulture;
                _cardetail.Info9 = ddlGender.GetGender();
                _cardetail.Info10 = usrDOB.GetDate().ToString("dd-MMM-yyyy");
                _cardetail.Info11 = ddlOccupation.GetOccupation();
                _cardetail.Info12 = "";// ddlJobNature.GetJobNature();
                _cardetail.Info13 = "";// ddlMaritalStatus.GetMaritalStatus();
                _cardetail.Info14 = "";// ddlYearDriveSg.Text;
                _cardetail.Info15 = "";// ddlSalutation.GetSalutation();
                _cardetail.RefCEUserId = UserId;
            }

            //RefUserId only update
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            _carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            _retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            CarDetailTHDB cardb = new CarDetailTHDB();
            cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
                //divNewErrorMessage.Visible = true;
                //lblCarInsProfileMessage.Text = "Error found in car quote profile update";
                lblMessage.Text = "Error found in car quote profile update";
            }
        }

        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            if (_useraccountdb.IsAlreadyExist(txtEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
            {
                //divNewErrorMessage.Visible = true;
                lblMessage.Text = Resources.Menu.EmailAlreadyRegister; //"Email address is already registered!";
                txtEmailAddress.ControlStyle.CssClass = "validationError";
                _retVal = 0;
            }
            else
            {
                Profile _userprofile = new Profile();
                ProfileDB _userprofiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                long _result = -1;
                //divNewErrorMessage.Visible = false;
                lblMessage.Visible = false;

                _useraccount.Email = txtEmailAddress.Text.ToLower();

                //Random _random = new Random();
                string _authcode = txtMobileNo.GetPhoneNo();
                //Sakthi on 21 Jan 2011
                //_authcode = "C" + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();
                //_authcode = _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();

                _useraccount.AuthCode = _authcode;

                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;

                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;

                if (_result > 0)
                {
                    _userprofile.Salutation = ""; //ddlSalutation.GetSalutation();
                    _userprofile.FirstName = Server.HtmlEncode(txtFirstName.Text);
                    _userprofile.SurName = Server.HtmlEncode(txtSurName.Text);

                    DateTime _dtDOB = new DateTime(1900, 1, 1);
                    _userprofile.DOB = _dtDOB;

                    _userprofile.DOB = usrDOB.GetDate();
                    _userprofile.Gender = Convert.ToChar(ddlGender.GetGender());
                    _userprofile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;                    
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobileNo.GetPhoneNo();


                        
                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        //SendMailToUser(_useraccount.Email, Session[CE.Global.General.UserName].ToString(), _contact.Mobile);
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = General.GetUTCDateTime();
        _loghis.EndTime = General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;

            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;

            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            //_loginfo.Info1 = Request.Browser.Tables;
            //_loginfo.Info2 = Request.Browser.Platform;
            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }
    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {        
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
       return _retVal;
    }


    protected void imgbtnLogin_Click(object sender, EventArgs e)
    {
        if (AutoLogin(100))
        {
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());

            }

            Int64 _carId = 0;

            if (Session[General.CarId] != null)
            {
                _carId = Convert.ToInt64(Session[General.CarId].ToString());
            }
            else
            {

                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/class-2plus.aspx", Page);
                Response.Redirect(_redirectUrl);
            }

            if (_userId > 0)
            {
                inputLoginHide.Value = "1";

                //update RefIds
                CarDetailTHDB cardb = new CarDetailTHDB();
                cardb.UpdateCarDetailPolicy(_carId, _userId);

                //vsCarProfile.Visible = false;
                //divNewErrorMessage.Visible = false;

                mpePassword.Hide();
                divExisting.Visible = false;
                //ShowCustomerDetail(_userId);

                inputLoginCount.Value = "0";

                //this.Page_Load(this, null);
                //Response.Redirect("profile.aspx");

            }

        }
        else
        {

            Int32 logincount = Convert.ToInt32(inputLoginCount.Value.Trim());
            inputLoginCount.Value = (logincount + 1).ToString();

            if (logincount == 2)
            {
                inputHideSignal.Value = "1";
            }
            else if (logincount >= 3)
            {
                this.btnPasswordClose_Click(this, null);
            }
            else
            {
                mpePassword.Show();
            }
        }

    }

    private bool AutoLogin(int LoginType)
    {
        bool isLoggedin = false;
        AccountStatus _accountstatus = new AccountStatus();
        AccountStatusDB _accountstatusdb = new AccountStatusDB();
        AccountDB _accountdb = new AccountDB();
        //Check Customer Account

        Account _account = _accountdb.GetUserAccount(txtExEmail.Text.ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));

        if (_account != null)
        {
            if (CheckUserLoginCached(_account.CEID.ToString()))
            {
                _accountstatus = _accountstatusdb.GetAccountStatus(_account.CEID, 400);

                if (Server.HtmlDecode(txtExAuthCode.Text) == _account.AuthCode)
                {
                    if (_account.Status == true)
                    {
                        isLoggedin = true;

                        if (_account.Info1 == "0")
                        {
                            //Reset Email Fail Message
                            _account.Info1 = "";
                            _account.Info2 = "";
                            _accountdb.Insert(_account);
                        }

                        _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                        lblEmailMessage.Visible = false;
                        GetUserInformation(_account);
                        SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                        CE.Global.General.CreateUpdateUserLoginCached(Page);
                        _account = null;
                        //if (LoginType == 100)
                        //{
                        //    //Response.Redirect("profile.aspx");
                        //    Response.Redirect("carAndpolicy_details.aspx");
                        //}
                        //else
                        //{
                        //    if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
                        //        Response.Redirect("~/User/saved-quotes.aspx?resulttitle=100");
                        //    else
                        //    {
                        //        Response.Redirect("~/User/EditProfile.aspx");
                        //    }
                        //}
                    }
                    else
                    {
                        lblEmailMessage.Visible = true;
                        lblEmailMessage.Text = "Your email has been blocked!";
                    }
                }
                else
                {
                    _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 0);
                    lblEmailMessage.Visible = true;
                    lblEmailMessage.Text = Resources.Menu.EmailPasswordIncorrect;//"Email address or password is incorrect.";
                }
            }
            else
            {
                //Response.Redirect("UserMessage.aspx?ErrorCode=1993");
                //Response.Redirect("~/user/usermessage.aspx?mt=UM&ec=1993");
                _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                Session["UMMSG"] = "UM,1993";
                Response.Redirect(_redirectUrl);
            }
        }
        else
        {
            lblEmailMessage.Visible = true;
            lblEmailMessage.Text = Resources.Menu.EmailPasswordIncorrect;
        }

        return isLoggedin;
    }

    protected void btnPasswordClose_Click(object sender, EventArgs e)
    {
        inputLoginCount.Value = "0";

        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/class-2plus.aspx", Page);
        Response.Redirect(_redirectUrl);
    }

    private bool CheckUserLoginCached(string UserId)
    {
        bool _retValue = false;
        string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.UserCacheName");
        sKey += UserId;
        if (HttpContext.Current.Cache[sKey] == null)
        {
            _retValue = true;
        }
        else
        {
            _retValue = false;
        }
        return _retValue;
    }
    private void GetUserInformation(Account _account)
    {
        DateTime dtNow = new DateTime();
        dtNow = General.GetUTCDateTime();
        Session[CE.Global.General.UserId] = _account.CEID;
        Session[CE.Global.General.UserTypeId] = _account.UserTypeId;

        if (_account.UserTypeId == Convert.ToInt32(CE.Global.CEUserType.Provider))
        {
            CE.Provider.ProviderCompanyLink _comlink = new CE.Provider.ProviderCompanyLink();
            CE.Provider.ProviderCompanyLinkDB _comlinkdb = new CE.Provider.ProviderCompanyLinkDB();
            _comlink = _comlinkdb.GetProviderCompanyId(_account.CEID);
            if (_comlink != null)
            {
                Session[CE.Global.General.ProviderCompanyId] = _comlink.ProviderCompanyId;
            }
        }

        Session[CE.Global.General.UserEmail] = _account.Email;
        Session[CE.Global.General.StartTime] = dtNow.ToString();
        bool isProfileComplete = false;
        bool isContactComplete = false;

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _contact = _contactdb.GetContact(_account.CEID);

        _profile = _profiledb.GetProfile(_account.CEID);

        if (_contact != null)
        {
            isContactComplete = true;
            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        }
        else
        {
            Session[CE.Global.General.UserPhoneNo] = null;
        }

        if (_profile != null)
        {
            if (_profile.FirstName != null && _profile.FirstName != string.Empty)
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName) + " " + Server.HtmlDecode(_profile.FirstName);
            }
            else
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
            }

            if (!string.IsNullOrEmpty(_profile.IDType) &&
                !string.IsNullOrEmpty(_profile.IDNo) &&
                _profile.IDNo.Length == 9)
            {
                Session[CE.Global.General.UserICNumber] = _profile.IDType + " " + _profile.IDNo;
            }

            if (_profile.Status.ToLower() == "complete")
            {
                isProfileComplete = true;
            }
            else
            {
                isProfileComplete = false;
            }
        }
        else
        {
            Session[CE.Global.General.UserName] = null;
        }

        if (isProfileComplete && isContactComplete)
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
        }
        else
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "0";
        }

    }

    private void ShowCustomerDetailByCar(Int64 CarId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();

        _cardetail = _cardetaildb.GetCar(CarId, 0);
        if (_cardetail != null)
        {
            if (_cardetail.Info5.Length > 0 &&
                _cardetail.Info6.Length > 0 &&
                _cardetail.Info7.Length > 0 &&
                _cardetail.Info8.Length > 0 &&
                _cardetail.Info9.Length > 0 &&
                _cardetail.Info10.Length > 0 &&
                _cardetail.Info11.Length > 0 &&
                _cardetail.Info12.Length > 0 &&
                _cardetail.Info13.Length > 0 &&
                _cardetail.Info14.Length > 0)
            {
                txtEmailAddress.Text = _cardetail.Info5;
                txtMobileNo.PhoneNo = _cardetail.Info6;
                txtSurName.Text = _cardetail.Info7;
                if (_cardetail.Info8.Length > 0)
                {
                    txtFirstName.Text = _cardetail.Info8;
                }
                ddlGender.Gender = _cardetail.Info9;
                DateTime _dtDOB = Convert.ToDateTime(_cardetail.Info10);
                usrDOB.Year = _dtDOB.Year;
                usrDOB.Month = _dtDOB.Month;
                usrDOB.Day = _dtDOB.Day;

                ddlOccupation.Occupation = _cardetail.Info11;
                //ddlJobNature.JobNature = _cardetail.Info12;
                //ddlMaritalStatus.MaritalStatus = _cardetail.Info13;
                //ddlYearDriveSg.Text = _cardetail.Info14;
                //ddlSalutation.Saluation = _cardetail.Info15;

                SetPassword(false);
            }
            else
            {
                if (Session[General.UserId] != null)
                {
                    ShowCustomerDetail(Convert.ToInt64(Session[General.UserId].ToString()));
                }
            }
        }
    }

    private void ShowCustomerDetail(Int64 UserId)
    {
        _profile = new CE.User.Profile();
        _profiledb = new ProfileDB();
        _contact = new Contact();
        _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            //ddlSalutation.Saluation = _profile.Salutation;
            txtFirstName.Text = _profile.FirstName;
            txtSurName.Text = _profile.SurName;

            //ddlMaritalStatus.MaritalStatus = _profile.MaritalStatus.ToString();
            ddlOccupation.Occupation = _profile.Occupation.ToString();
            //ddlJobNature.JobNature = _profile.JobNature;

            //ddlYearDriveSg.Text = _profile.YearDriveSg.ToString();
            ddlGender.Gender = _profile.Gender.ToString();

            usrDOB.Day = _profile.DOB.Day;
            usrDOB.Month = _profile.DOB.Month;
            usrDOB.Year = _profile.DOB.Year;

            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtMobileNo.PhoneNo = _contact.Mobile;
                txtEmailAddress.Text = _contact.Email;
                txtEmailAddress.ReadOnly = true;

                SetPassword(false); //disable
            }

            //Disable DOB, Gender and Year of Driving Exp Sg
            if (Session[CE.Global.General.UserTypeId].ToString() == "400")
            {
                if (Session[General.UserProfileAndContactComplete].ToString() == "1")
                {
                    usrDOB.IsEnabled = false;
                    ddlGender.IsEnabled = false;
                }
            }
            _profile = null;
        }
    }

    private void SetPassword(bool bStatus)
    {
        divPassword.Visible = bStatus;
        divReEnterPassword.Visible = bStatus;
        rfvPassword.Enabled = bStatus;
        rfvReEnterPassword.Enabled = bStatus;

        txtEmailAddress.Enabled = bStatus;
    }

    #endregion


}
